<template>
  <div class="business-info-page">
    <!-- 头部 -->
    <div class="header">
      <div class="back" @click="$router.back()">
        <i class="iconfont icon-back"></i>
      </div>
      <div class="title">{{ businessInfo?.businessName }}</div>
    </div>

    <!-- 商家信息 -->
    <div class="business-info" v-if="businessInfo">
      <div class="business-header">
        <img :src="businessInfo.businessImg" :alt="businessInfo.businessName">
        <div class="info">
          <h2>{{ businessInfo.businessName }}</h2>
          <p>{{ businessInfo.businessExplain }}</p>
          <div class="delivery-info">
            <span>起送￥{{ businessInfo.starPrice }}</span>
            <span>配送￥{{ businessInfo.deliveryPrice }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 食品列表 -->
    <div class="food-list">
      <div class="food-item" v-for="item in foodList" :key="item.foodId">
        <div class="food-img">
          <img :src="item.foodImg" :alt="item.foodName">
        </div>
        <div class="food-info">
          <h3>{{ item.foodName }}</h3>
          <p class="desc">{{ item.foodExplain }}</p>
          <div class="price-action">
            <div class="price">￥{{ item.foodPrice }}</div>
            <div class="action">
              <!-- 减号按钮 -->
              <div class="minus" v-if="getCartCount(item.foodId)" @click="updateCart(item, -1)">
                <i class="iconfont icon-minus">-</i>
              </div>
              <!-- 数量显示 -->
              <div class="count" v-if="getCartCount(item.foodId)">
                {{ getCartCount(item.foodId) }}
              </div>
              <!-- 加号按钮 -->
              <div class="plus" @click="updateCart(item, 1)">
                <i class="iconfont icon-plus">+</i>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 购物车栏 -->
    <div class="cart-bar" v-if="totalPrice > 0">
      <div class="cart-info">
        <div class="total-price">
          <span class="price">￥{{ totalPrice }}</span>
          <span class="delivery">另需配送费￥{{ businessInfo?.deliveryPrice }}</span>
        </div>
      </div>
      <div class="checkout" 
           :class="{ active: totalPrice >= (businessInfo?.starPrice || 0) }"
           @click="goToCheckout">
        {{ totalPrice >= (businessInfo?.starPrice || 0) ? 
           '去结算' : 
           `还差￥${(businessInfo?.starPrice || 0) - totalPrice}起送` }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const route = useRoute()
const businessInfo = ref(null)
const foodList = ref([])
const cartItems = ref([])
const userId = localStorage.getItem('userId')

// 获取商家信息
const getBusinessInfo = async () => {
  try {
    const res = await axios.get('/business/getBusinessById', {
      params: { businessId: route.query.businessId }
    })
    businessInfo.value = res.data
  } catch (error) {
    console.error('获取商家信息失败:', error)
  }
}

// 获取食品列表
const getFoodList = async () => {
  try {
    const res = await axios.get('/food/listFoodByBusinessId', {
      params: { businessId: route.query.businessId }
    })
    foodList.value = res.data
  } catch (error) {
    console.error('获取食品列表失败:', error)
  }
}

// 获取购物车信息
const getCartInfo = async () => {
  if (!userId) return
  try {
    const res = await axios.get('/cart/listCart', {
      params: {
        userId,
        businessId: route.query.businessId
      }
    })
    cartItems.value = res.data
  } catch (error) {
    console.error('获取购物车信息失败:', error)
  }
}

// 获取某个食品在购物车中的数量
const getCartCount = (foodId) => {
  const item = cartItems.value.find(item => item.foodId === foodId)
  return item ? item.quantity : 0
}

// 更新购物车
const updateCart = async (food, num) => {
  if (!userId) {
    router.push('/login')
    return
  }

  const currentCount = getCartCount(food.foodId)
  const newCount = currentCount + num

  try {
    if (newCount === 0) {
      // 删除
      await axios.post('/cart/removeCart', null, {
        params: {
          userId,
          businessId: route.query.businessId,
          foodId: food.foodId
        }
      })
    } else if (currentCount === 0) {
      // 新增
      await axios.post('/cart/saveCart', null, {
        params: {
          userId,
          businessId: route.query.businessId,
          foodId: food.foodId
        }
      })
    } else {
      // 更新
      await axios.post('/cart/updateCart', null, {
        params: {
          userId,
          businessId: route.query.businessId,
          foodId: food.foodId,
          quantity: newCount
        }
      })
    }
    await getCartInfo()
  } catch (error) {
    console.error('更新购物车失败:', error)
  }
}

// 计算总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    const food = foodList.value.find(f => f.foodId === item.foodId)
    return total + (food?.foodPrice || 0) * item.quantity
  }, 0)
})

// 去结算
const goToCheckout = () => {
  if (totalPrice.value < (businessInfo.value?.starPrice || 0)) return
  if (!userId) {
    router.push('/login')
    return
  }
  router.push({
    path: '/order',
    query: {
      businessId: route.query.businessId
    }
  })
}

onMounted(() => {
  getBusinessInfo()
  getFoodList()
  if (userId) {
    getCartInfo()
  }
})
</script>

<style scoped>
.business-info-page {
  padding-top: 44px;
  padding-bottom: 50px;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 44px;
  background: #0097ff;
  color: #fff;
  display: flex;
  align-items: center;
  padding: 0 15px;
  z-index: 100;
}

.back {
  padding: 10px;
  margin-left: -10px;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 16px;
}

.business-info {
  background: #fff;
  padding: 15px;
}

.business-header {
  display: flex;
}

.business-header img {
  width: 80px;
  height: 80px;
  margin-right: 15px;
}

.info h2 {
  margin: 0 0 8px;
  font-size: 20px;
}

.info p {
  margin: 0 0 8px;
  font-size: 12px;
  color: #666;
}

.delivery-info {
  font-size: 12px;
  color: #666;
}

.delivery-info span {
  margin-right: 10px;
}

.food-list {
  margin-top: 10px;
  background: #fff;
}

.food-item {
  display: flex;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.food-img {
  width: 80px;
  height: 80px;
  margin-right: 15px;
}

.food-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.food-info {
  flex: 1;
}

.food-info h3 {
  margin: 0 0 5px;
  font-size: 16px;
}

.desc {
  font-size: 12px;
  color: #666;
  margin-bottom: 10px;
}

.price-action {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  color: #ff6b01;
  font-size: 16px;
  font-weight: bold;
}

.action {
  display: flex;
  align-items: center;
  justify-content: center;
}

.minus, .plus {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #0097ff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.iconfont {
  font-size: 26px;
}

.count {
  margin: 0 10px;
  min-width: 20px;
  text-align: center;
}

.cart-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 15px;
  border-top: 1px solid #eee;
}

.cart-info {
  flex: 1;
}

.total-price .price {
  font-size: 20px;
  margin-right: 10px;
}

.total-price .delivery {
  font-size: 12px;
  color: #666;
}

.checkout {
  width: 110px;
  height: 40px;
  background: #ccc;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 20px;
  margin-left: 15px;
}

.checkout.active {
  background: #0097ff;
  cursor: pointer;
}
</style>